package cn.enilu.guns.admin.equipment.service;

import cn.enilu.guns.admin.common.constant.device.ParamConstant;
import cn.enilu.guns.admin.common.constant.device.TableConstant;
import cn.enilu.guns.admin.core.util.EntranceDataUtil;
import cn.enilu.guns.admin.equipment.dto.DeviceInfo;
import cn.enilu.guns.admin.equipment.transform.GetDeviceDataTransform;
import cn.enilu.guns.bean.entity.door.DoorInfo;
import cn.enilu.guns.bean.entity.door.TimeInfo;
import cn.enilu.guns.bean.entity.system.User;
import cn.enilu.guns.utils.Lists;
import com.jwz.app.AdmsSdkService;
import com.jwz.app.DateUtils;
import com.jwz.service.AdmsSdkServiceImpl;
import com.jwz.service.SdkResult;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EntranceGuardService {
///todo 实现与设备通讯功能
    private AdmsSdkServiceImpl admsSdkServiceImpl = new AdmsSdkServiceImpl() ;
//    private AdmsSdkServiceImpl admsSdkServiceImpl ;

    /**
     * 获取句柄，后续根据此句柄，进行设备的操作、查询等
     * @param ip
     * @return
     */
    public int getHCommPro(String ip){
        //建立设备连接
        SdkResult sdkResult = admsSdkServiceImpl.connectExt("protocol=TCP,ipaddress="+ip+",port=4370,timeout=3000,passwd=",new int[4]);
        return sdkResult.getResult();
    }

    /**
     * 根据IP获取设备的门禁控制类型,及序列号
     * @param ip
     * @return
     */
    public String getControllerTypeAndSerialNumber(String ip){
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "0";
        }
        //4.获取设备参数，根据传入的item，动态获取想得到的信息
        String item = ParamConstant.LOCK_COUNT+ ","+ParamConstant.SERIAL_NUMBER;
        SdkResult sdkResult = admsSdkServiceImpl.getDeviceParam(hCommPro,new byte[1024*1024],item);
        if(sdkResult.getSuccess()){
            return sdkResult.getData();
        }
        return "0";
    }
    /**
     * 根据IP获取设备IP,网关，子网掩码
     * @param ip
     * @return
     */
    public String getIp(String ip){
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "0";
        }
        //4.获取设备参数，根据传入的item，动态获取想得到的信息
        String item = ParamConstant.IP_ADDRESS+ ","+ParamConstant.GATE_IP_ADDRESS+ ","+ParamConstant.NET_MASK;
        SdkResult sdkResult = admsSdkServiceImpl.getDeviceParam(hCommPro,new byte[1024*1024],item);
        if(sdkResult.getSuccess()){
            return sdkResult.getData();
        }
        return "0";
    }

    /**
     * 向设备发送数据
     */
    public String addDataToDoor(DoorInfo doorInfo,String tableName, Object o){
        //建立设备连接
        String ip = doorInfo.getEquipmentInfo().getIpAddress();
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "设备连接失败";
        }
        String data = o.toString();
        SdkResult sdkResult = admsSdkServiceImpl.setDeviceData(hCommPro,tableName,data,"");

        if(sdkResult.getResult() == 0){
            return doorInfo.getDoorName() + "人员更新成功";
        }else{
            return doorInfo.getDoorName() + "人员更新失败，请检查设备后，手动更新";
        }
    }
    /**
     * 向设备发送数据
     */
    public String addDataToDoor(DoorInfo doorInfo,String tableName, List<?> list){
        //建立设备连接
        String ip = doorInfo.getEquipmentInfo().getIpAddress();
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "设备连接失败";
        }
        String data = EntranceDataUtil.parse(list);
        SdkResult sdkResult = admsSdkServiceImpl.setDeviceData(hCommPro,tableName,data,"");

        if(sdkResult.getResult() == 0){
            return doorInfo.getDoorName() + "人员更新成功";
        }else{
            return doorInfo.getDoorName() + "人员更新失败，请检查设备后，手动更新";
        }
    }
    /**
     * 向设备发送删除人员
     */
    public String removeDataFromDoor(DoorInfo doorInfo,String tableName, List<?> list){
        //建立设备连接
        String ip = doorInfo.getEquipmentInfo().getIpAddress();
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "设备连接失败";
        }
        String data = EntranceDataUtil.parse(list);
        SdkResult sdkResult = admsSdkServiceImpl.deleteDeviceData(hCommPro,tableName,data,"");

        if(sdkResult.getResult() == 0){
            return doorInfo.getDoorName() + "人员更新成功";
        }else{
            return doorInfo.getDoorName() + "人员更新失败，请检查设备后，手动更新";
        }
    }
    public String removeDataFromDoor(DoorInfo doorInfo,String tableName, Object obj){
        //建立设备连接
        String ip = doorInfo.getEquipmentInfo().getIpAddress();
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "设备连接失败";
        }
        String data = obj.toString();
        SdkResult sdkResult = admsSdkServiceImpl.deleteDeviceData(hCommPro,tableName,data,"");

        if(sdkResult.getResult() == 0){
            return doorInfo.getDoorName() + "人员更新成功";
        }else{
            return doorInfo.getDoorName() + "人员更新失败，请检查设备后，手动更新";
        }
    }
    /**
     * 设备设置时段
     */
    public String setTimezoneToDoor(DoorInfo doorInfo, TimeInfo timeInfo){
        //建立设备连接
        String ip = doorInfo.getEquipmentInfo().getIpAddress();
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "设备连接失败";
        }

        String data = timeInfo.toString();
        SdkResult sdkResult = admsSdkServiceImpl.setDeviceData(hCommPro,TableConstant.TABLE_TIMEZONE,data,"");

        if(sdkResult.getResult() == 0){
            return doorInfo.getDoorName() + "设置时段成功";
        }else{
            return doorInfo.getDoorName() + "设置时段失败，请检查设备后，手动更新";
        }
    }

    /**
     * 设置设备IP
     */
    public String setIpAddress(DeviceInfo deviceInfo){
        int hCommPro = getHCommPro(deviceInfo.getIpAddress());//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "设备连接失败";
        }
        SdkResult sdkResult = admsSdkServiceImpl.setDeviceParam(hCommPro,deviceInfo.transformToDeviceData());
        if(sdkResult.getResult() == 0){
            return "设置IP时段成功";
        }else{
            return "设置IP失败，请检查设备后，手动更新";
        }
    }
    /**
     * 搜索设备
     * @return
     */
    public List searchDevice(){
        SdkResult sdkResult = admsSdkServiceImpl.searchDevice();
//        List<String> collect = Arrays.asList(sdkResult.getData().split(",")).stream().collect(Collectors.toList());
//        String str = "LockCount=1,~SerialNumber=1234,IPAddress=10.10.10.10,NetMask=1.1.1.1" +
//                "\r\n~SerialNumber=111,LockCount=4,IPAddress=11.11.11.11,NetMask=2.2.2.2";
//        List<String> collect = Arrays.asList(str.split(",")).stream().collect(Collectors.toList());
        if(!sdkResult.getSuccess()){
            return null;
        }
        String str = sdkResult.getData();
        List<String> collect = Arrays.asList(str.split("\r\n"));

        List<DeviceInfo> deviceInfos = Lists.newArrayList();
        for (String deviceInfoStr:collect) {
            DeviceInfo deviceInfo = GetDeviceDataTransform.transformToDeviceInfo(deviceInfoStr);
            deviceInfos.add(deviceInfo);
        }
        return deviceInfos;
    }

    /**
     * 同步时间到设备
     */
    public String setTimeToDevice(String ip){
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "设备连接失败";
        }
        SdkResult sdkResult = admsSdkServiceImpl.setDeviceParam(hCommPro,ParamConstant.DATE_TIME +"="+ DateUtils.convertDate2Str(new Date()));//时间转换成时间戳算法请参照DateUtils*/
        if(sdkResult.getResult() == 0){
            return "同步时间成功";
        }else{
            return "同步时间失败，请检查设备！";
        }
    }

    /**
     * 获取设备事件记录
     */
    public String getTransactionToDevice(String ip){
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "0";
        }
        byte[] callback = new byte[1024*1024];
        SdkResult sdkResult = admsSdkServiceImpl.getDeviceData(hCommPro,callback,TableConstant.TABLE_TRANSACTION,"*","","NewRecord");
        if(sdkResult.getSuccess()){
            return sdkResult.getData();
        }
        return "0";
    }
    /**
     * 清空设备数据
     */
    public String cleanDeviceData(String ip,String tableName){
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "0";
        }
        byte[] callback = new byte[1024*1024];
        SdkResult sdkResult = admsSdkServiceImpl.deleteDeviceData(hCommPro,tableName,"*","");
        if(sdkResult.getSuccess()){
            sdkResult.getData();
        }
        return "0";
    }
    /**
     * 获取设备实时记录
     */
    public String getRTLog(String ip){
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        if(hCommPro <= 0){
            return "0";
        }
        byte[] callback = new byte[1024*1024];
        SdkResult sdkResult = admsSdkServiceImpl.getRTLog(hCommPro,callback );
        if(sdkResult.getResult() == 1){
            String eventCode = sdkResult.getData().split(",")[4];
            if("255".equals(eventCode)) {
                return "0";
            }
        }
        if(sdkResult.getSuccess()){
            return sdkResult.getData();
        }
        return "0";
    }
    public String getRTLog(int hCommPro){
        byte[] callback = new byte[1024*1024];
        SdkResult sdkResult = admsSdkServiceImpl.getRTLog(hCommPro,callback );
        if(sdkResult.getResult() == 1){
            String eventCode = sdkResult.getData().split(",")[4];
            if("255".equals(eventCode)) {
                return "0";
            }
        }
        if(sdkResult.getSuccess()){
            return sdkResult.getData();
        }
        return "0";
    }
    /**
     * 检查设备是否在线
     * @param ip
     * @return
     */
    public boolean checkDeviceOnline(String ip){
        int hCommPro = getHCommPro(ip);//获取句柄，后续根据此句柄，进行设备的操作、查询等
        return hCommPro > 0;
//        return  true;
    }
}
